package com.xy_pro.xymanager.helper;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XMLParser {

    /**
     * 解析微信推送的XML消息，转换为Map
     * @param xml 微信推送的XML字符串
     * @return 包含消息字段的Map
     */
    public static Map<String, String> parse(String xml) throws DocumentException {
        Map<String, String> result = new HashMap<>();

        // 1. 读取XML字符串
        SAXReader reader = new SAXReader();
        Document document = reader.read(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));

        // 2. 获取根节点
        Element root = document.getRootElement();

        // 3. 递归解析所有子节点
        parseElement(root, result);

        return result;
    }

    /**
     * 递归解析XML节点
     */
    private static void parseElement(Element element, Map<String, String> result) {
        // 存储当前节点的文本值
        if (element.isTextOnly()) {
            result.put(element.getName(), element.getTextTrim());
        } else {
            // 解析子节点
            List<Element> childElements = element.elements();
            for (Element child : childElements) {
                parseElement(child, result);
            }
        }
    }
}
